// +build windows
// +build 386
package main

import (
	"UpdateTools/model"
	"encoding/xml"
	"fmt"
	"github.com/lxn/walk"
	. "github.com/lxn/walk/declarative"
	"github.com/lxn/win"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"time"
)

type myApp struct {
	title string
	msg   *walk.TextEdit
	mw    *walk.MainWindow
}

type SoftUpdateStruct struct {
	text        string
	serviceName string
	LastUpdate  *walk.Label
	btnOpenDir  *walk.PushButton
	btnReXML    *walk.PushButton
}

type AutoUpdateService struct {
	XMLName      xml.Name    `xml:"Config"`
	NewServerUrl string      `xml:"newServerUrl,attr"`
	Enabled      string      `xml:"enabled,attr"`
	XmlnsXSD     string      `xml:"xmlns:xsd,attr"`
	XmlnsXSI     string      `xml:"xmlns:xsi,attr"`
	LocalFile    []LocalFile `xml:"LocalFile"`
}

type LocalFile struct {
	Path        string `xml:"path,attr"`
	Url         string `xml:"url,attr"`
	Lastver     string `xml:"lastver,attr"`
	Size        int64  `xml:"size,attr"`
	NeedRestart string `xml:"needRestart,attr"`
	Zipped      string `xml:"zipped,attr"`
}

type Conf struct {
	RootDir           string `xml:"RootDir"`
	UpdateServerIP    string `xml:"UpdateServerIP"`
	Path              string `xml:"Path"`
	UrlPath           string `xml:"UrlPath"`
	Applications      string `xml:"Applications"`
	FASP              string `xml:"FASP"`
	BAS               string `xml:"BAS"`
	XMK               string `xml:"XMK"`
	YSBZ              string `xml:"YSBZ"`
	AutoUpdateService string `xml:"AutoUpdateService"`
	DBIP              string `xml:"DBIP"`
	DBPort            string `xml:"DBPort"`
	DBPassWord        string `xml:"DBPassWord"`
	DBUserName        string `xml:"DBUserName"`
	DBName            string `xml:"DBName"`
}

var (
	path                                                                                 string
	XMLPath                                                                              string
	urlpath                                                                              string
	NewServerUrl                                                                         string
	app                                                                                  myApp
	SoftUpdateStructFASP, SoftUpdateStructBAS, SoftUpdateStructXMK, SoftUpdateStructYSBZ SoftUpdateStruct
)

func init() {
	app.title = "一体化2.0前端升级"
	SoftUpdateStructFASP = SoftUpdateStruct{
		text:        "平台",
		serviceName: "FASPUpdate",
	}
	SoftUpdateStructBAS = SoftUpdateStruct{
		text:        "基础信息",
		serviceName: "BASUpdate",
	}
	SoftUpdateStructXMK = SoftUpdateStruct{
		text:        "项目库",
		serviceName: "XMKupdate",
	}
	SoftUpdateStructYSBZ = SoftUpdateStruct{
		text:        "预算编制",
		serviceName: "YSBZUpdate",
	}
}

func main() {
	model.DbInit()
	_ = getWindows()

	walk.App().SetProductName(app.title)
	walk.App().SetOrganizationName("dwt")
	var SoftUpdateStructFASPLastUpdate = model.LastUpdateTime(SoftUpdateStructFASP.serviceName)
	var SoftUpdateStructBASLastUpdate = model.LastUpdateTime(SoftUpdateStructBAS.serviceName)
	var SoftUpdateStructXMKLastUpdate = model.LastUpdateTime(SoftUpdateStructXMK.serviceName)
	var SoftUpdateStructYSBZLastUpdate = model.LastUpdateTime(SoftUpdateStructYSBZ.serviceName)
	_ = SoftUpdateStructFASP.LastUpdate.SetText(SoftUpdateStructFASPLastUpdate)
	_ = SoftUpdateStructBAS.LastUpdate.SetText(SoftUpdateStructBASLastUpdate)
	_ = SoftUpdateStructXMK.LastUpdate.SetText(SoftUpdateStructXMKLastUpdate)
	_ = SoftUpdateStructYSBZ.LastUpdate.SetText(SoftUpdateStructYSBZLastUpdate)
	// 打开目录按钮
	SoftUpdateStructFASP.btnOpenDir.Clicked().Attach(func() {
		OpenDir(SoftUpdateStructFASP)
	})
	SoftUpdateStructBAS.btnOpenDir.Clicked().Attach(func() {
		OpenDir(SoftUpdateStructBAS)
	})
	SoftUpdateStructXMK.btnOpenDir.Clicked().Attach(func() {
		OpenDir(SoftUpdateStructXMK)
	})
	SoftUpdateStructYSBZ.btnOpenDir.Clicked().Attach(func() {
		OpenDir(SoftUpdateStructYSBZ)
	})
	// 重写XML按钮
	SoftUpdateStructFASP.btnReXML.Clicked().Attach(func() {
		ReXML(SoftUpdateStructFASP)
	})
	SoftUpdateStructBAS.btnReXML.Clicked().Attach(func() {
		ReXML(SoftUpdateStructBAS)
	})
	SoftUpdateStructXMK.btnReXML.Clicked().Attach(func() {
		ReXML(SoftUpdateStructXMK)
	})
	SoftUpdateStructYSBZ.btnReXML.Clicked().Attach(func() {
		ReXML(SoftUpdateStructYSBZ)
	})

	app.mw.Show()
	app.mw.Run()
}

func InitConfig() Conf {
	file, _ := os.Open("conf.xml") // For read access.
	data, _ := ioutil.ReadAll(file)

	v := Conf{}
	_ = xml.Unmarshal(data, &v)
	return v
}

// 打开目录
func OpenDir(SoftUpdate SoftUpdateStruct) {
	config := InitConfig()
	switch SoftUpdate.serviceName {
	case "FASPUpdate":
		path = config.RootDir + config.Path + config.FASP
	case "BASUpdate":
		path = config.RootDir + config.Path + config.Applications + "\\" + config.BAS
	case "XMKupdate":
		path = config.RootDir + config.Path + config.Applications + "\\" + config.XMK
	case "YSBZUpdate":
		path = config.RootDir + config.Path + config.Applications + "\\" + config.YSBZ
	default:
		path = config.RootDir + config.Path
	}
	cmd := exec.Command("cmd", "/C", "explorer", path)
	err := cmd.Start()
	if err != nil {
		log.Fatal(err)
	}
}

// 重写XML
func ReXML(SoftUpdate SoftUpdateStruct) {
	config := InitConfig()
	localFile := LocalFile{}
	switch SoftUpdate.serviceName {
	case "FASPUpdate":
		path = config.RootDir + config.Path + config.FASP
		XMLPath = path + "\\" + config.AutoUpdateService
		urlpath = config.UpdateServerIP + config.UrlPath + config.FASP
		NewServerUrl = config.UpdateServerIP + config.UrlPath + config.FASP + "/" + config.AutoUpdateService
	case "BASUpdate":
		path = config.RootDir + config.Path + config.Applications + "\\" + config.BAS
		XMLPath = path + "\\" + config.AutoUpdateService
		urlpath = config.UpdateServerIP + config.UrlPath + config.Applications + "/" + config.BAS
		NewServerUrl = config.UpdateServerIP + config.UrlPath + config.Applications + "/" + config.BAS + "/" + config.AutoUpdateService
	case "XMKupdate":
		path = config.RootDir + config.Path + config.Applications + "\\" + config.XMK
		XMLPath = path + "\\" + config.AutoUpdateService
		urlpath = config.UpdateServerIP + config.UrlPath + config.Applications + "/" + config.XMK
		NewServerUrl = config.UpdateServerIP + config.UrlPath + config.Applications + "/" + config.XMK + "/" + config.AutoUpdateService
	case "YSBZUpdate":
		path = config.RootDir + config.Path + config.Applications + "\\" + config.YSBZ
		XMLPath = path + "\\" + config.AutoUpdateService
		urlpath = config.UpdateServerIP + config.UrlPath + config.Applications + "/" + config.YSBZ
		NewServerUrl = config.UpdateServerIP + config.UrlPath + config.Applications + "/" + config.YSBZ + "/" + config.AutoUpdateService
	default:
		path = config.RootDir + config.Path
		XMLPath = path + "\\" + config.AutoUpdateService
		urlpath = config.UpdateServerIP + config.UrlPath
		NewServerUrl = config.UpdateServerIP + config.UrlPath + config.FASP + "/" + config.AutoUpdateService
	}
	dir_list, _ := ioutil.ReadDir(path)
	var AutoUpdateService = AutoUpdateService{NewServerUrl: NewServerUrl,
		Enabled: "true", XmlnsXSI: "http://www.w3.org/2001/XMLSchema-instance", XmlnsXSD: "http://www.w3.org/2001/XMLSchema-instance"}
	for _, v := range dir_list {
		if v.Name() == "AutoUpdateService.xml" {
			continue
		}
		filePath := path + "\\" + localFile.Path
		localFile.Path = v.Name()
		localFile.Size = v.Size()
		localFile.NeedRestart = "false"
		localFile.Zipped = "false"
		localFile.Url = urlpath + "/" + v.Name()
		localFile.Lastver = HandelFile(filePath, localFile, SoftUpdate.serviceName)
		AutoUpdateService.LocalFile = append(AutoUpdateService.LocalFile, localFile)
		//localFile.Lastver = sumCMD5(filePath)
	}
	output, err := xml.MarshalIndent(&AutoUpdateService, "", "\t\t")
	if err != nil {
		fmt.Println("Error marshalling to XML:", err)
		return
	}

	err = ioutil.WriteFile(XMLPath, []byte(xml.Header+string(output)), 0644)
	if err != nil {
		fmt.Println("Error writing XML to file:", err)
		return
	}
	walk.MsgBox(nil, "重写完成！", "重写完成！", walk.MsgBoxIconInformation)
}

func showMsg(msg string) {
	app.msg.AppendText(time.Now().Format("2006-01-02 15:04:05 "))
	app.msg.AppendText(msg)
	app.msg.AppendText("\r\n")
}

// 初始始化窗体
func getWindows() error {
	icon, _ := walk.NewIconFromResourceId(3)
	err := MainWindow{
		Visible:  false,
		AssignTo: &app.mw,
		Title:    app.title,
		Size:     Size{500, 360},
		Font:     Font{Family: "微软雅黑", PointSize: 9},
		Icon:     icon,
		Layout:   VBox{},
		Children: []Widget{
			GroupBox{
				Title:  "前端服务",
				Layout: Grid{Columns: 3},
				Children: []Widget{
					Label{Text: SoftUpdateStructFASP.text, MinSize: Size{220, 30}, TextColor: walk.RGB(255, 255, 0)},
					Label{AssignTo: &SoftUpdateStructFASP.LastUpdate, Text: "正在运行", MinSize: Size{80, 30}},
					Composite{
						Layout:  HBox{},
						MaxSize: Size{132, 30},
						Children: []Widget{
							PushButton{
								AssignTo: &SoftUpdateStructFASP.btnOpenDir,
								MaxSize:  Size{60, 30},
								Text:     "打开目录",
							},
							PushButton{
								AssignTo: &SoftUpdateStructFASP.btnReXML,
								MaxSize:  Size{60, 30},
								Text:     "重写XML",
							},
						},
					},
					Label{Text: SoftUpdateStructBAS.text},
					Label{AssignTo: &SoftUpdateStructBAS.LastUpdate, Text: "正在运行"},
					Composite{
						Layout:  HBox{},
						MaxSize: Size{132, 30},
						Children: []Widget{
							PushButton{
								AssignTo: &SoftUpdateStructBAS.btnOpenDir,
								MaxSize:  Size{60, 30},
								Text:     "打开目录",
							},
							PushButton{
								AssignTo: &SoftUpdateStructBAS.btnReXML,
								MaxSize:  Size{60, 30},
								Text:     "重写XML",
							},
						},
					},
					Label{Text: SoftUpdateStructXMK.text},
					Label{AssignTo: &SoftUpdateStructXMK.LastUpdate, Text: "正在运行"},
					Composite{
						Layout:  HBox{},
						MaxSize: Size{132, 30},
						Children: []Widget{
							PushButton{
								AssignTo: &SoftUpdateStructXMK.btnOpenDir,
								MaxSize:  Size{60, 30},
								Text:     "打开目录",
							},
							PushButton{
								AssignTo: &SoftUpdateStructXMK.btnReXML,
								MaxSize:  Size{60, 30},
								Text:     "重写XML",
							},
						},
					},
					Label{Text: SoftUpdateStructYSBZ.text},
					Label{AssignTo: &SoftUpdateStructYSBZ.LastUpdate, Text: "正在运行"},
					Composite{
						Layout:  HBox{},
						MaxSize: Size{132, 30},
						Children: []Widget{
							PushButton{
								AssignTo: &SoftUpdateStructYSBZ.btnOpenDir,
								MaxSize:  Size{60, 30},
								Text:     "打开目录",
							},
							PushButton{
								AssignTo: &SoftUpdateStructYSBZ.btnReXML,
								MaxSize:  Size{60, 30},
								Text:     "重写XML",
							},
						},
					},
				},
			},
			Composite{
				Layout: HBox{},
				Children: []Widget{
					HSpacer{},
					PushButton{
						MinSize: Size{121, 30},
						Text:    "关闭",
						OnClicked: func() {
							walk.App().Exit(0)
						},
					},
				},
			},
		},
		OnSizeChanged: func() {
			_ = app.mw.SetSize(walk.Size(Size{500, 360}))
		},
	}.Create()
	winLong := win.GetWindowLong(app.mw.Handle(), win.GWL_STYLE)
	// 不能调整窗口大小，禁用最大化按钮
	win.SetWindowLong(app.mw.Handle(), win.GWL_STYLE, winLong & ^win.WS_SIZEBOX & ^win.WS_MAXIMIZEBOX & ^win.WS_SIZEBOX)
	// 设置窗体生成在屏幕的正中间，并处理高分屏的情况
	// 窗体横坐标 = ( 屏幕宽度 - 窗体宽度 ) / 2
	// 窗体纵坐标 = ( 屏幕高度 - 窗体高度 ) / 2
	_ = app.mw.SetX((int(win.GetSystemMetrics(0)) - app.mw.Width()) / 2 / app.mw.DPI() * 96)
	_ = app.mw.SetY((int(win.GetSystemMetrics(1)) - app.mw.Height()) / 2 / app.mw.DPI() * 96)
	return err
}
